<template>
  <div class="app-container">
    <el-row :gutter="10" style="height: 100%">
      <el-col :span="17" style="height: 100%">
        <el-card class="box-card card-div">
          <el-divider content-position="left"><span class="divider-css">▶挂号信息◀</span></el-divider>
          <div style="margin: 0px 0px -10px 0px">
            <el-row>
              <el-col :span="5">
                <el-form-item label="挂号科室">
                  <base-dept-tree ref="baseDeptTreeRef" :clinicalSignStr="'5,6,9,10'" :org-id="userInfo.orgId"
                                  :value="deptId"
                                  style="width: 100%" @deptSelect="deptSelect"/>
                </el-form-item>
              </el-col>
              <el-col :span="5" class="ml10">
                <el-form-item label="挂号医生">
                  <user-select :id="doctorId" ref="userSelectRef" :org-id="userInfo.orgId"
                               style="width: 100%"
                               @userChange="userChange"/>
                </el-form-item>
              </el-col>
              <el-col :span="6"></el-col>
              <el-col :span="7">
                <el-form-item>
                  <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div ref="registInfoDiv" class="regist-info-div">
            <el-card v-for="(item, index) in todayList" :id="'card-' + index" :key="index" class="card-info"
                     shadow="hover" @click="cardClick(item, index)">
              <template #header>
                <div>
                  {{ item.clinicIndexVo.name }}
                  <div class="mr5" style="float: right">
                    {{ parseFloat(item.totalPrice).toFixed(2) }}元
                  </div>
                </div>
              </template>
              <div :class="'card-div' + index" class="center-div">
                科&nbsp;&nbsp;&nbsp;室：{{ item.clinicIndexVo.deptName }}
              </div>
              <div :class="'card-div' + index" class="center-div">
                医&nbsp;&nbsp;&nbsp;师：{{
                  !item.clinicIndexVo.doctorName ? "/" : item.clinicIndexVo.doctorName
                }}
              </div>
              <div :class="'card-div' + index" class="center-div">
                限号数：{{ item.limitNum }}
                <el-tooltip v-if="item.limitNum !== 0 && item.currentRegisNum >= item.limitNum"
                            class="box-item"
                            content="加号" effect="dark" placement="top">
                  <el-button style="float: right; height: 19px; width: 0px" type="warning"
                             @click.stop="addRegister(item, index)">
                    <template #icon>
                      <i-ep-plus/>
                    </template>
                  </el-button>
                </el-tooltip>
              </div>
              <div :class="'card-div' + index" class="center-div">
                已挂号：{{ item.currentRegisNum }}
              </div>
              <div :class="'card-div' + index" class="center-div">
                预约数：{{ item.limitPreNum }}
              </div>
            </el-card>
          </div>
          <el-divider content-position="left"><span class="divider-css">▶患者基本信息◀</span></el-divider>
          <register-form ref="registerFormRef" :org-id="userInfo.orgId" @save-register="saveRegister"/>
        </el-card>
      </el-col>
      <el-col :span="7" style="height: 100%">
        <el-card class="box-card card-div">
          <el-divider content-position="left"><span class="divider-css">▶费用信息◀</span></el-divider>
          <el-row> 费用明细</el-row>
          <div class="regist-info-div" style="height: 143px; background-color: #ffffff; position: relative">
            <el-descriptions v-if="priceListVoList.length > 0" :border="true" :column="1"
                             class="mt5 mr5 mb5 ml5">
              <el-descriptions-item v-for="(priceInfo, index) in priceListVoList" :key="priceInfo.priceId"
                                    min-width="200px">
                <template #label>
                  <div class="cell-item">
                    {{ priceInfo.itemName }}
                  </div>
                </template>
                {{ parseFloat(priceInfo.price).toFixed(2) }}元
              </el-descriptions-item>
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">合计：</span>
                  </div>
                </template>
                <span class="ys-css"> {{ parseFloat(totalPrice).toFixed(2) }}</span>元
              </el-descriptions-item>
            </el-descriptions>
            <div v-else style="
                line-height: 105px;
                position: absolute;
                left: 50%;
                transform: translateX(-50%);
              ">
              暂无数据
            </div>
          </div>
          <el-row class="mt10">
            支付类型明细
            <div class="regist-info-div" style="
                height: calc(100% - 390px);
                background-color: #ffffff;
                position: relative;
              ">
              <div style="height: 300px; overflow-y: auto">
                <pay-way-list v-if="clinicForRegistId || isNotShow" ref="payWayListRef"
                              :inp_or_outp="inpOrOutp"
                              :total-price="totalPrice" @set-net-receipts="payWayBlur"/>
                <div v-else style="
                    line-height: 105px;
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                  ">
                  暂无数据
                </div>
              </div>
            </div>
          </el-row>
          <div style="margin-top: 30px">
            <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">应收金额:</span>
                  </div>
                </template>
                <span class="ys-css"> {{ totalPrice }} </span>元
              </el-descriptions-item>
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">实收金额:</span>
                  </div>
                </template>
                <span class="ys-css"> {{ netReceipts }} </span>元
              </el-descriptions-item>
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">找&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;零:</span>
                  </div>
                </template>
                <span class="ys-css"> {{ retChange }} </span>元
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <el-button class="ml10" style="position: absolute; bottom: 7px; right: 20px" type="success"
                     @click="chargeOk">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            确认收费
          </el-button>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import {listClinicForRegist, updateClinicForRegist} from "@/api/base/clinicForRegist";
import {addRegisterAndPatient} from "@/api/finance/registPayType";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import RegisterForm from "@/views/finance/register/registerForm.vue";

const dictStore = useDictStoreHook();
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "register_type",
    "payment_method",
    "patient_medical_source",
    "sys_yes_no",
    "medical_insurance_type",
    "sys_user_sex",
    "marriage_dict",
    "nation_dict",
    "nationality_dict",
    "relationship_dict",
    "profession_dict",
    "education_dict",
    "pay_way_dict"
  )
);
const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
const deptId = ref("")
const doctorId = ref("")
const clinicForRegistId = ref("")
const doctorName = ref("")
const deptName = ref("")
const inpOrOutp = ref<number>(1);
const isNotShow = ref(false)
const registerFormRef = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const baseDeptTreeRef = ref();
const userSelectRef = ref();
const payWayListRef = ref();
let registQueryParam = <any>{};
const registInfoDiv = ref();
const todayList = ref<any>([]);
// 费用明细
const priceListVoList = ref<any>([]);

// 应收总金额
const totalPrice = ref<any>(0.0);
// 实收金额
const netReceipts = ref<number>(0.0);
// 找零
const retChange = ref<number>(0.0);

getListClinicForRegist();

function getListClinicForRegist() {
  registQueryParam.orgId = userInfo.orgId;
  registQueryParam.clinicDateStr = proxy.$parseTime(new Date(), "{y}-{m}-{d}");
  listClinicForRegist(registQueryParam).then((res: any) => {
    todayList.value = res.data;
  });
}

/** 挂号点击事件 */
function cardClick(item, index) {
  clinicForRegistId.value = "";
  if (item.limitNum !== 0 && item.currentRegisNum === item.limitNum) {
    return ElMessage.warning("当前号已挂完，不能挂号");
  } else {
    clickCssChange(index);
    item.priceListVoList.forEach((priceListVo: any) => {
      const costs = priceListVo.price * priceListVo.clinicVsPriceVo.amount;
      priceListVo.costs = costs;
      priceListVo.charges = costs;
    });
    priceListVoList.value = item.priceListVoList;
    totalPrice.value = Number(item.totalPrice);
    clinicForRegistId.value = item.clinicForRegistId;
    doctorId.value = item.clinicIndexVo.doctorId;
    doctorName.value = item.clinicIndexVo.doctorName;
    deptId.value = item.clinicIndexVo.deptId;
    deptName.value = item.clinicIndexVo.deptName;
    nextTick(() => {
      const payWayDictList = payWayListRef.value.getPayWayDictList();
      payWayListRef.value.initPayWayDictSelect()
      if (payWayDictList.length === 1) {
        payWayListRef.value.setFirstCost(totalPrice.value);
      } else {
        payWayListRef.value.removePayWayAll()
        payWayListRef.value.inpSetFirstPayWay()
        payWayListRef.value.setFirstCost(totalPrice.value);
      }
      payWayListRef.value.payWayChange("1", 0);
      payWayListRef.value.payWayBlur();
    });
    // nextTick(() => {
    //     payWayListRef.value.removePayWayAll()
    //     payWayListRef.value.initPayWayDictSelect()
    //     payWayListRef.value.inpSetFirstPayWay(totalPrice.value);
    //     payWayListRef.value.payWayChange("1", 0);
    //     payWayListRef.value.setFirstCost(Number(item.totalPrice));
    // });
  }
}

/** 科室点击事件 */
function deptSelect(node) {
  if (!node) {
    registQueryParam.deptIdParam = "";
  } else {
    registQueryParam.deptIdParam = node.deptId;
  }
  getListClinicForRegist();
}

// 收费按钮点击事件
function chargeOk() {
  if (!clinicForRegistId.value) {
    return ElMessage.error("请先选择挂号信息后，再收费");
  }
  if (retChange.value < 0) {
    return ElMessage.error("实收金额小于应收金额，请检查费用信息是否正确。");
  }
  // 患者信息校验
  registerFormRef.value.saveRegisterValidate()
}

function saveRegister(form: any) {
  ElMessageBox.confirm("确定要收费吗？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let submitForm: any = {};
      form.clinicForRegistId = clinicForRegistId.value;
      form.doctorId = doctorId.value;
      form.doctorName = doctorName.value;
      form.deptId = deptId.value;
      form.deptName = deptName.value;
      form.clinicChage = totalPrice.value;
      // 是否诊间录入 1 是  :   2 否
      submitForm.isRoomEntry = "2"
      submitForm.patientInfo = form;
      submitForm.onSiteAmbulanceStationId = form.onSiteAmbulanceStationId;
      // submitForm.clinicRecordBo = clinicRecordBo;
      submitForm.payWayInfoList = payWayListRef.value.getPayWayDictList();
      submitForm.payWayInfoList.forEach(item => {
        item.costs = item.charges
        item.type = item.moneyType
      })
      submitForm.registrationItemBoList = priceListVoList.value;
      submitForm.clinicMasterCostBo = {};
      submitForm.orgId = form.orgId;
      addRegisterAndPatient(submitForm).then((res: any) => {
        if (res.code === 200) {
          // initPayWayDictSelect();
          nextTick(() => {
            registerFormRef.value.resetPatient()
            payWayListRef.value.removePayWayAll();
          })
          clinicForRegistId.value = ''
          priceListVoList.value = [];
          // payWayDictList.value = [firstPayWay]
          totalPrice.value = 0.0;
          // 实收金额
          netReceipts.value = 0.0;
          // 找零
          retChange.value = 0.0;
          getListClinicForRegist();
          ElMessage.success("挂号成功");
        } else {
          ElMessage.success("挂号失败");
        }
      });
    })
}

// 初始化支付方式option都为可选状态
function initPayWayDictSelect() {
  nextTick(() => {
    payWayListRef.value.initPayWayDictSelect();
  });
}

// 根据支付方式填写的金额自动计算应收和找零
function autoChargeFun() {
  retChange.value = Number((netReceipts.value - totalPrice.value).toFixed(2));
}

// 支付方式input金额焦点消失事件
function payWayBlur(netReceiptsThis: number) {
  netReceipts.value = Number(netReceiptsThis);
  autoChargeFun();
}

/** 用户点击事件 */
function userChange(obj) {
  if (!obj) {
    registQueryParam.doctorParam = "";
  } else {
    registQueryParam.doctorParam = obj.userId;
  }
  getListClinicForRegist();
}


function resetQuery() {
  baseDeptTreeRef.value.setSelectedValue();
  userSelectRef.value.setSelectedValue();
  registQueryParam.deptIdParam = "";
  registQueryParam.doctorParam = "";
  getListClinicForRegist();
}

function handleQuery() {
  getListClinicForRegist();
}

/** 挂号框点击样式改变事件 */
function clickCssChange(index) {
  for (let i = 0; i < todayList.value.length; i++) {
    if (index === i) {
      const cardRef = "card-" + index;
      const carDiv = "card-div" + index;
      const myDivParent = document.getElementById(cardRef);
      //@ts-ignore
      myDivParent.className = "click-div";
      const myDivs = document.querySelectorAll("." + carDiv);
      myDivs.forEach((myDiv) => {
        //@ts-ignore
        myDiv.style.borderBottom = "0.5px dashed #f4f4f4";
      });
    } else {
      const cardRef = "card-" + i;
      const carDiv = "card-div" + i;
      const myDivParent = document.getElementById(cardRef);
      //@ts-ignore
      myDivParent.classList.remove("click-div");
      //@ts-ignore
      myDivParent.className = "card-info el-card";
      const myDivs = document.querySelectorAll("." + carDiv);
      myDivs.forEach((myDiv) => {
        //@ts-ignore
        myDiv.style.borderBottom = "0.5px dashed #ababab";
      });
    }
  }
}

/** 加号 */
function addRegister(item, index) {
  ElMessageBox.confirm("确定要加号吗？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const obj = {
        clinicForRegistId: toRaw(item.clinicForRegistId),
      };
      updateClinicForRegist(obj).then(() => {
        ElMessage.success("加号成功");
        getListClinicForRegist();
        item.limitNum += 1;
        cardClick(item, index);
      });
    })
    .catch(() => {
    });
}
</script>
<script lang="ts">
export default {
  name: "registerIndex",
};
</script>

<style scoped>

.el-divider--horizontal {
  margin: 10px 0 !important;
}

.card-div {
  height: 100%;
  overflow-y: auto;
}

.click-div {
  background-color: #1284fd;
  color: #f4f4f4;
  height: 160px;
  width: 165px;
  margin: 5px;
  float: left;
  border-radius: 10px;
}

.card-info {
  height: 160px;
  width: 165px;
  margin: 5px;
  float: left;
  border-radius: 10px;
}

.age-margin {
  margin-right: -15px;
}

.center-div {
  height: 20px;
  border-bottom: 0.5px dashed #ababab;
  margin: 0px -8px 5px -8px;
  font-size: 13px;
}

:deep(.el-card__body) {
  padding-top: 0px !important;
  padding-bottom: 0px !important;
  height: calc(100% - 20px);
}

:deep(.el-card__header) {
  padding: 3px 0px 3px 7px !important;
  font-size: 13px;
  min-height: 20px;
  border-bottom: 1px solid #ababab;
}


:deep(.el-divider--horizontal) {
  margin: 10px 0px;
}

:deep(.payWayMoney-label .el-form-item__label) {
  color: #de1f1f;
  font-size: 15px;
}

</style>
